<?php
	require("include/includes.php");
	require("include/getIP.php");
	
	//fil d'ariane
	$ariane = array(
		array(
			'href' => "index.php",
			'name' => "Home"
		),
		array(
			'href' => "profile.php",
			'name' => "Profile"
		),
		array(
			'href' => "profile_edit.php",
			'name' => "Edit profile"
		)
	);
	
		
	if(!isset($_SESSION["user"]))
	{
		header('location:profile.php'); //TODO trouver une page plus intelligente... o_O
	}
	
	$user = $_SESSION["user"];
	
	
	// Champs obligatoires ('nom du champ' => 'nom affiché lors d'une erreur')
	$requieredFields = Array(
		'country' => 'Country', 
		'email' => 'Personnal email',
		'birthdate' => 'Date of birth');
	
	// Valeurs initiales
	$valueCountry 		= postOrCustom('country', 'France');
	$valuePassword  	= postOrCustom('password', '');
	$valuePassword2  	= postOrCustom('password2', '');
	$valueEmail  		= postOrCustom('email', '');
	$valueDisplayed_email=postOrCustom('displayed_email', '');
	$valueBirthdate 	= postOrCustom('birthdate', $user->getBirthdate());
	$valueDescription	= postOrCustom('description', '');
	$sqlBirthdate = '';
	$displayBirthdate = '';
	$errors = Array();
	
	$countries = Country::getAll();
	
	
	// Format de la date de naissance
	if(!empty($valueBirthdate))
	{
		$date_string = str_replace('/', '-', $valueBirthdate); // => so $date_string = Y-m-d (db) OR d-m-Y (post)
		try {
			$sqlBirthdate = new DateTime($date_string);
			$displayBirthdate = date_format($sqlBirthdate, "d/m/Y");
			$sqlBirthdate = date_format($sqlBirthdate, "Y-m-d");
		}
		catch(Exception $e) {
			$errors['birthdate'] = 'There is a mistake in your birthdate format, you should use this format: DD/MM/YYYY or YYYY-MM-DD';
			$displayBirthdate = $valueBirthdate;
		}
	}
	
	//TODO: faire 2 submit différents, un pour changer le pass, et un pour le reste
	
	/// --- VALIDATION DU FORMULAIRE ---
	if(isset($_POST['submit']))
	{ //$errors[] = 'post detected';
		if(!verifyCsrfToken())
		{
			$errors['csrf'] = 'Security token missing!';
		}
		else // CSRF ok
		{
			if(!empty($valuePassword2))
			{
				//TODO require strong password
				if(Player::checkLogin($user->getNickname(), $valuePassword))
				{
					$user->setPassword($valuePassword2);
				}
				else
				{
					$errors['password'] = 'You didn\'t type your current password correctly';
				}
			}
		}
		
		if(empty($errors))
		{
			// vérification des champs obligatoires
			foreach($requieredFields as $reqField => $reqText)
			{
				if(!isset($_POST[$reqField]) || empty($_POST[$reqField]))
				{
					$errors[$reqField] = 'Please fill the field "'.$reqText.'"';
				}
			}

			// Format des emails
			if(!empty($valueEmail) && !emailIsValid($valueEmail))
			{
				$errors['email'] = 'Your private email is not a valid email adress';
			}
			if(!empty($valueDisplayed_email) && !emailIsValid($valueDisplayed_email))
			{
				$errors['displayed_email'] = 'Your public email is not a valid email adress';
			}
		}
		// Traitement des données (si aucune erreur)
		if(empty($errors))
		{
			$user->setDescription($valueDescription);
			$user->setCountry_id($valueCountry); //TODO verif si country existe? (secu)
			$user->setEmail($valueEmail); //TODO lien confirmation toussa toussa
			$user->setDisplayed_email($valueDisplayed_email);
			$user->setBirthdate($sqlBirthdate);
			
			if($user->save())
			{
				header('location:profile.php');
			}
			else
			{
				$errors[''] = 'Oops! I can\'t save your profile!';
			}
		}
	}
	/*
	$template = $twig->loadTemplate('register.html');
	$template->display(array(
		'pageTitle' 		=> 'ctr4ever - Registration',
		'contenu' 			=> 'Contenu de la page',
		'countries' 		=> $countries,
		'valueCountry'		=> $valueCountry,
		'valueNickname'		=> $valueNickname,
		'valuePassword'		=> $valuePassword,
		'valueEmail'		=> $valueEmail,
		'valueDisplayed_email'=> $valueDisplayed_email,
		'valueBirthdate'	=> $valueBirthdate,
		'valueDescription'	=> $valueDescription,
		'errors'			=> $errors,
		'crsfToken' 		=> csrfField()
	));
	*/
	
	$template = $twig->loadTemplate('register.html');
	$template->display(array(
		'pageTitle' 		=> 'Edit my profile',
		'edit' 				=> true,
		'countries' 		=> $countries,
		'valueCountry'		=> $user->getCountry(),
		'valueNickname'		=> $user->getNickname(),
		'valuePassword'		=> $valuePassword,
		'valueEmail'		=> $user->getEmail(),
		'valueDisplayed_email'=> $user->getDisplayed_email(),
		'valueBirthdate'	=> $displayBirthdate,
		'valueDescription'	=> $user->getDescription(),
		'errors'			=> $errors,
		'crsfToken' 		=> csrfField()
	));

?>